package com.example.dormitorysystem.common.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dormitorysystem.entity.*;
import com.example.dormitorysystem.mapper.*;
import com.example.dormitorysystem.service.BedsService;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static java.util.Collections.shuffle;

/**
 * @author chen huilong
 * @data 2022/11/27
 */
@Component
@RabbitListener(queues = "orders")
public class ReceiveOrderMessage {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private RoomsMapper roomsMapper;

    @Resource
    private BedsMapper bedsMapper;

    @Resource
    private BedsService bedsService;

    @Resource
    private GroupsUserMapper groupsUserMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @RabbitHandler
    public void QueueReceiver(Orders order) {

        System.out.println("正在处理订单：" + order.getId());

        order.setFinishTime(new Date());
        // 查询该用户是否已经有宿舍
        Beds beds = bedsMapper.selectByUid(order.getUid());
        if (beds != null) {
            order.setStatus(2);
            order.setResultContent("已有宿舍，不能重复抢");
            ordersMapper.updateById(order);
            return;
        }

        // 用户信息
        Integer uid = order.getUid();
        Users users = usersMapper.selectById(uid);
        Integer gender = users.getGender();
        Integer buildingId = order.getBuildingId();

        //为了方便分配宿舍，在寝室中添加数据可以用的床数
        //第一次分配，只分配到小于四个床位的房间中
        QueryWrapper<Rooms> roomsQueryWrapper = new QueryWrapper<>();
        roomsQueryWrapper.eq("building_id", order.getBuildingId())
                .eq("gender", gender).eq("is_valid", 1).eq("is_del", 0)
                .lt("available_bed",4);
        List<Rooms> rooms = roomsMapper.selectList(roomsQueryWrapper);
        // 随机打乱
        shuffle(rooms);

        //非组队单人抢宿舍
        if (order.getGroupId() == 0) {
            for (Rooms room : rooms) {
                Beds bed = bedsMapper.selectOneBedByRoomId(room.getId());
                if (bed != null) {
                    //修改可用的床位数
                    roomsMapper.selectById(room.getId());
                    room.setAvailableBeds(room.getAvailableBeds()-1);
                    roomsMapper.updateById(room);
                    //修改具体的床位信息
                    bed.setUid(order.getUid());
                    bed.setStatus(1);
                    bedsMapper.updateById(bed);
                    // 修改订单状态
                    order.setStatus(1);
                    order.setRoomId(room.getId());
                    order.setResultContent("恭喜，抢宿舍成功！");
                    ordersMapper.updateById(order);

                    return;
                }
            }
        } else {
            //todo 修改组队抢宿舍的逻辑
            //四人寝室和六人寝室分别处理
            GroupsUser groupsUser = groupsUserMapper.selectOneByUid(uid);
            QueryWrapper<GroupsUser> groupsUserQueryWrapperTarget = new QueryWrapper<>();
            groupsUserQueryWrapperTarget.eq("group_id", groupsUser.getGroupId());
            Integer memberCount = groupsUserMapper.selectCount(groupsUserQueryWrapperTarget);

            // 队伍成员信息
            List<GroupsUser> members = groupsUserMapper.selectMemberByGroupId(order.getGroupId());
            for (Rooms room : rooms) {
                // 当前宿舍的可用床位
                List<Beds> bedCountsByRoomId = bedsMapper.getBedCountsByRoomId(room.getId());
                if (bedCountsByRoomId.size() >= members.size()) {

                    for (int i = 0; i < members.size(); i++) {
                        Beds bed = bedCountsByRoomId.get(i);
                        bed.setUid(members.get(i).getUid());
                        bed.setStatus(1);
                    }
                    //只需要将宿舍直接分配给当前的订单


                    // 批量修改床位表
                    bedsService.saveOrUpdateBatch(bedCountsByRoomId);
                    // 修改订单状态
                    order.setStatus(1);
                    order.setRoomId(room.getId());
                    order.setResultContent("恭喜，抢宿舍成功！");
                    ordersMapper.updateById(order);

                    return;
                }
            }
        }
        order.setStatus(2);
        order.setResultContent("没有合适的宿舍，选择其他宿舍楼重新提交");
        ordersMapper.updateById(order);
    }
}
